package com.xiaolin.Thread.synchronization;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName BuyTicketByAtomic
 * @Description TODO
 * @Detail 原子类实现线程安全
 * @Author MyPC
 * @Date 2020/10/5
 * @Version 1.0
 */
public class BuyTicketByAtomic {
    public static void main(String[] args) {
        TicketManager tm1=new TicketManager();
        TicketManager tm2=new TicketManager();
        tm1.start();
        tm2.start();
    }
}

class TicketManager extends Thread{
    // 所有该线程的实例都共享这一份静态变量
    private static AtomicInteger atomicInteger=new AtomicInteger(100);
    @Override
    public void run() {
        for (int i=0;i<100;i++){
            if(atomicInteger.get()==0){
                System.out.println(Thread.currentThread()+"共抢到了"+i+"张票");
                break;
            }
            System.out.println(Thread.currentThread()+"抢到了第"+atomicInteger.getAndDecrement()+"张票");
        }

    }
}
